package com.team2.cyber_eye;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.team2.cyber_eye.ActivityHelpers.HistoryItemDao;
import com.team2.cyber_eye.ActivityHelpers.HistoryListAdapter;
import com.team2.cyber_eye.ActivityHelpers.Util;
import com.team2.cyber_eye.background_task.CheckInternetConnectionTask;
import com.team2.cyber_eye.background_task.CheckInternetConnectionTask.LoadingTaskFinishedListener;
import com.team2.shared.HistoryItem;

public class Home extends CyberActivity implements LocationListener, LoadingTaskFinishedListener {
	
	private Uri mImageCaptureUri;
	private String mFileName;
	static final int MAX_ITEM_HISTORY = 20;
	static List<HistoryItem> history;
	boolean isGPSEnabled = false;
	ProgressDialog progDialog;
	String internetConStatus = "";
	
	static HistoryListAdapter historyListAdapter;

	static HistoryItemDao historyItemDao;
	
	private static final int PICTURE_FROM_CAMERA = 1;
	private static final int PICTURE_FROM_FILE = 3;
	
	private static final int CROP_DONE = 2;
	private static final int IQE_DONE = 4;
	private static final int GATHER_USER_LOCATION = 5;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState, R.layout.activity_home, "CYBER-EYE");
		
		Button cameraButton = (Button) findViewById(R.id.button_camera);
		cameraButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { CameraOnClick(); } });
		
		Button shopButton = (Button) findViewById(R.id.button_shop);
		shopButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { ShopByTextClick(); } });
		
		Button barcodeButton = (Button) findViewById(R.id.button_barcode);
		barcodeButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { BarcodeClick(); } });
		
		Button galleryButton = (Button) findViewById(R.id.button_gallery);
		galleryButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { GalleryClick(); } });
		
		Button settingsButton = (Button) findViewById(R.id.button_settings);
		settingsButton.setOnClickListener(new OnClickListener(){ 
			@Override public void onClick(View v) 
			{ 
				SettingsClick();
			}
		});
		
		initHistory();
		initHistoryListView();
		
		if(!Util.isInternetConnected()){
			showDialog(0);
			
			CheckInternetConnectionTask obj = new CheckInternetConnectionTask(this, this);
			obj.execute();
		}
	}
	
	private void initHistory() {
		historyItemDao = new HistoryItemDao(this);
		history = historyItemDao.loadAll();
		if (history == null) {
			history = new ArrayList<HistoryItem>();
		}
	}

	private void initHistoryListView() {
		historyListAdapter = new HistoryListAdapter(this);
		Button historyButton = (Button) findViewById(R.id.button_history);
		historyButton.setOnClickListener(new OnClickListener(){ 
			@Override public void onClick(View v) 
			{ 
				if(history.size() > 0){
					Intent intent = new Intent(Home.this,HistoryActivity.class);
					startActivity(intent);
				}else{
					Util.DisplayIssue(getApplicationContext(), "No images to display");
				}
				
			} 
		});
	}
	
	void CameraOnClick()
	{
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		
		mFileName = "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
		
		mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mFileName));
		
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

		try 
		{
			intent.putExtra("return-data", true);
			
			startActivityForResult(intent, PICTURE_FROM_CAMERA);
		}
		catch (ActivityNotFoundException e)
		{
			Util.DisplayError(this, "Error Initializing camera", e);
		}
	}
	
	void ShopByTextClick()
	{
		Intent intent = new Intent(Home.this, SearchByText.class);
		intent.putExtra("FromIQE", "no");
    	startActivity(intent);
	}
	
	void BarcodeClick()
	{
		Intent intent = new Intent(Home.this, BarcodeActivity.class);
    	startActivity(intent);
	}
	
	void GalleryClick()
	{
    	Intent intent = new Intent();
		
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICTURE_FROM_FILE);
	}
	
	void SettingsClick(){
		Intent intent = new Intent(Home.this, Options.class);
		startActivity(intent);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    
	    Bundle extras = null;
	    if (data != null)
	    	extras = data.getExtras();
	    
	    switch (requestCode) {
		    case PICTURE_FROM_CAMERA:
		    	//try { doCrop(); } catch (Exception ex) { Util.DisplayError(this, "Error croping image", ex); }
		    	if (resultCode != RESULT_OK) return;
		    	
		    	startIQE(null);
		    	break;
		    	
		    case PICTURE_FROM_FILE: 
		    	//try { mImageCaptureUri = data.getData(); doCrop(); } catch (Exception ex) { Util.DisplayError(this, "Error croping image", ex); }
				if (resultCode != RESULT_OK) return;
		    	mImageCaptureUri = data.getData();
		    	startIQE(null);
		    	break;
		    	
		    case CROP_DONE:
		    	if (resultCode != RESULT_OK) return;
		    	//doIQE();
		    	Util.DisplayIssue(this, "Warning you should not see this crop issue");
		    	break;
		    	
		    case IQE_DONE:	
		    	if (resultCode != RESULT_OK) return;

		        if (extras != null)
		        {
		            String productName = extras.getString("name");
		            String queryId = extras.getString("queryId");
		            
		            InputStream is;
		            Bitmap bmp = null;
		            try {
						is = this.getContentResolver().openInputStream(mImageCaptureUri);
						
						bmp = Util.decodeSampledBitmapFromResourceMemOpt(is, 100, 100);
						
					} catch (FileNotFoundException e) {
						
						Util.DisplayIssue(getApplicationContext(), "Error compressing image");
					}
	    			
		            
		            HistoryItem item = new HistoryItem();
		            
		            item.setId(queryId);
		            item.setLabel(productName);
		            item.setImageUri(mImageCaptureUri.toString());
		            item.setIqeOrBarcode("iqe");
		            if(bmp != null){
		            	
		            	String filePath = Util.FilePath(mImageCaptureUri);
		            	
		            	Bitmap rotatedBitmap = Util.RotateBitmap(bmp, filePath);
						
						if(rotatedBitmap != null){
							item.setThumb(rotatedBitmap);
						}else{
							item.setThumb(bmp);
						}	            	
		            }
		            		            
		            if (history.size() > MAX_ITEM_HISTORY)
		    			history.remove(0);

		    		history.add(item);
		    		
		    		historyItemDao.saveAll(history);
					

		    		Intent intent = new Intent(this, SearchByText.class);
		           
		        	intent.setData(mImageCaptureUri);
		        	intent.putExtra("text", productName);
		        	intent.putExtra("FromIQE", "yes");
		        	intent.putExtra("iqeOrBarcode", "iqe");
		        	this.startActivity(intent);
		        }
		    	break;	
		    	
		    case GATHER_USER_LOCATION:
		    	Util.StartLocationGathering(getApplicationContext(), this);
		    	break;
	    }
	}
    
	private void startIQE(Bitmap photo)
	{
		Intent intent = new Intent(this, IQE_Progress.class);      
		intent.putExtra("iqeOrBarcode", "iqe");
    	intent.setData(mImageCaptureUri);
    	this.startActivityForResult(intent, IQE_DONE);
	}
	
	private void doIQE()
	{
		Bitmap bmp = null;
		try
		{
			Uri uri = mImageCaptureUri;
			InputStream is = this.getContentResolver().openInputStream(uri);
			bmp = BitmapFactory.decodeStream(is);
			bmp = Util.LimitBitmap(bmp, 500);
			startIQE(bmp);
		}
		catch (Exception ex)
		{
			Util.DisplayError(this, "Error loading image to crop\nPosible SD card coruption", ex);
			
			return;
		}
    	/*
        if (extras != null)
        {
        	try
        	{
	            Bitmap photo = (Bitmap)extras.get("data");
	            if (photo == null)
	            {
	            	Util.DisplayIssue(this, "Error loading cropped image it does not exist");
	            	return;
	            }
	            startIQE(photo);
        	}
        	catch (Exception ex)
        	{
        		Util.DisplayError(this, "Error loading cropped image\nPosible SD card coruption", ex);
			}
        }*/
	}
	
    private void doCrop() 
    {
		Intent intent = new Intent(Home.this, CropActivity.class);
		intent.setData(mImageCaptureUri);
		startActivityForResult(intent, CROP_DONE);
		
		/*final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
    	
    	Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");
        
        List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
        
        int CropAppCount = list.size();
        
        if (CropAppCount == 0)
        {	        
        	Util.DisplayIssue(this, "Can not find image crop app");
        	
            return;
        }
        else
        {
        	try
        	{
	        	intent.setData(mImageCaptureUri);
	            intent.putExtra("outputX", 250);
	            intent.putExtra("outputY", 250);
	            intent.putExtra("scale", true);
	            intent.putExtra("crop", true);
	            intent.putExtra("aspectX", 1);
	            intent.putExtra("aspectY", 1);
	            intent.putExtra("return-data", true);
	            
				if (CropAppCount == 1)
				{
					Intent i 		= new Intent(intent);
					ResolveInfo res	= list.get(0);
					
					i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
					
					startActivityForResult(i, CROP_FROM_CAMERA);
				}
				else
				{
				    for (ResolveInfo res : list) {
				    	final CropOption co = new CropOption();
				    	
				    	co.title 	= getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
				    	co.icon		= getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
				    	co.appIntent= new Intent(intent);
				    	
				    	co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
				    	
				        cropOptions.add(co);
				    }
				
				    CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
				    
				    AlertDialog.Builder builder = new AlertDialog.Builder(this);
				    builder.setTitle("Choose Crop App");
				    builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
				        public void onClick( DialogInterface dialog, int item ) {
				            startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
				        }
				    });
				
				    builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
				        @Override
				        public void onCancel( DialogInterface dialog ) {
				           
				            if (mImageCaptureUri != null ) {
				                getContentResolver().delete(mImageCaptureUri, null, null );
				                mImageCaptureUri = null;
				            }
				        }
				    } );
				    
				    AlertDialog alert = builder.create();
				    
				    alert.show();
				}
        	}
        	catch (Exception ex)
        	{
        		Util.DisplayError(this, "Error loading image cropper", ex);
        	}
        }*/
	}
    
    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.Theme_MyDialog))
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setMessage("Are you sure you want to close this activity?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            	Util.setInternetConnected(false);
                finish();    
            }

        })
        .setNegativeButton("No", null)
        .show();
    }

	public static List<HistoryItem> getHistory() {
		return history;
	}

	public static void setHistory(ArrayList<HistoryItem> history) {
		Home.history = history;
	}

	public static HistoryListAdapter getHistoryListAdapter() {
		return historyListAdapter;
	}

	public static void setHistoryListAdapter(HistoryListAdapter historyListAdapter) {
		Home.historyListAdapter = historyListAdapter;
	}

	public static HistoryItemDao getHistoryItemDao() {
		return historyItemDao;
	}

	public static void setHistoryItemDao(HistoryItemDao historyItemDao) {
		Home.historyItemDao = historyItemDao;
	}

	@Override
	public void onLocationChanged(Location location) {
		
		Util.setLatitude(location.getLatitude());
		Util.setLogitude(location.getLongitude());
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTaskFinished(String internetConnectionStatus) {
		
		internetConStatus = internetConnectionStatus;

		if(internetConnectionStatus.equals("Connection Available")){
			if(Util.isGPSEnabled(this))
				Util.StartLocationGathering(this, this);
		}else{
			Util.DisplayMessage(getApplicationContext(), internetConnectionStatus);
		}
				
		progDialog.dismiss();
	}
	
	@Override
	protected Dialog onCreateDialog(int id){
		progDialog = new ProgressDialog(this, R.style.Theme_MyDialog);
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setMessage("Checking Internet and GPS Connection...");
		progDialog.setTitle("In Progress");
		progDialog.setCanceledOnTouchOutside(false);
		progDialog.setCancelable(true);
		return progDialog;
	}
}
